import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import RegionTree from '@/components/biz/RegionTree';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import DataForm from './components/DataForm';
import ExpandedStationTable from './components/ExPandedStationTable'
import TauSimpleSelect from '@/components/TauSimpleSelect';

const Station = () => {
  return (
    <TauPage className="page-container-2">
      <CityList />
      <StationList />
    </TauPage>
  );
};

const CityList = observer(() => {
  const { busStationStore: store } = useStore();

  useEffect(() => { store.region = {}; }, []);

  return (
    <div className="left-panel" style={{ maxWidth: 220, minWidth: 220, padding: 10, borderRight: 'solid 1px var(--color-fill1-4)' }}>
      <RegionTree
        onRegion={(r) => { store.region = r; }}
        type={2}
      // maxLevel={1}
      />
    </div>
  );
});

const StationList = observer(() => {
  const { busStationStore: store } = useStore();
  const [modal, setModal] = useState({ visible: '', record: {} });
  const [selectData, setSelectData] = useState([]);
  const [expandAll, setExpandAll] = useState(false);
  const [companys, setCompanys] = useState([]);
  const [stationState, setStationState] = useState(2);
  const { cityId, type, cityName } = store.params;

  useEffect(() => {
    (async () => {
      store.regionData = await store.getTopItems('region');
      const res = await store.getCompany({ search: { isOperating: true }, pg: { size: 99, page: 0 } });
      setCompanys(res);
    })();
    return () => {
      setStationState(2);
    };
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { stationType, hot, cityId: id, state = 2, ...search } = params.values;
    if (stationType !== undefined) {
      _.merge(search, { extras: { 'transfer.value': stationType === '1' } });
    }
    if (hot?.[0] === 1) {
      _.merge(search, { extras: { 'hot.value': true } });
    }
    setStationState(state);
    store.search = {
      cityId: id,
      ...(state !== 3 ? { state: state != '1' } : {}),
      ...search,
    };
  };

  const handleCreate = () => {
    setModal({ visible: 'add', record: {} });
  };

  const handleBatchSetting = async () => {
    if (selectData.length === 0) {
      Message.warning({ content: t`请先勾选站点` });
      return;
    }
    Dialog.confirm({
      title: t`批量处理`,
      content: (
        <div style={{
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'center',
          alignItems: 'center',
        }}
        >
          <TauSimpleSelect
            data={store.regionData}
            placeholder="城市"
            onChange={(v, __, r) => {
              const { label } = r || {};
              store.params.cityId = v;
              store.params.cityName = label;
            }}
            style={{ width: 200, margin: '20px 0' }}
          />
          <TauSimpleSelect
            data={toSelectDataSource(ENUMS.type)}
            placeholder="标识"
            onChange={(v) => {
              store.params.type = v;
            }}
            style={{ width: 200 }}
          />
        </div>),
      onOk: async () => {
        if (!cityId || !type) {
          Message.error({ content: t`城市和标识必填！`, duration: 7000 });
        } else {
          await batch();
        }
      },
    });
    setModal({ visible: 'batch', record: {} });
  };

  async function batch() {
    try {
      const filterStation = toJS(store.stations).filter((p) => selectData.includes(p?.id));
      const toggleStation = filterStation.map((p) => ({
        ...p,
        cityId,
        type,
        cityName,
      }));
      await Promise.all(toggleStation.map((p) => {
        return store.update(p);
      }));
      Message.success({ content: t`批量操作成功` });
    } catch (error) {
      Message.error({ content: t`批量操作失败`, duration: 7000 });
    } finally {
      /* eslint-disable require-atomic-updates */
      store.params.cityId = null;
      store.params.cityName = null;
      store.params.type = null;
      setSelectData([]);
    }
  }

  const handleEditStation = (station) => {
    setModal({ visible: 'edit', record: station });
  };

  const handleCreateStation = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // 原站点信息
        const siteMapping = store.currentStationInfos;
        const stationALL = store.selectStationInfos;
        // 新加入站点信息
        const flatSelectStationInfos = Object.values(toJS(stationALL))
        const toggleSite = flatSelectStationInfos.map((p) => ({
          companyId: p.companyId,
          companyName: p.companyName,
          stationId: p.stationId,
          stationName: p.name,
          description: p.description,
          link: p.link,
          kind: p.kind,
          cityId: p.cityId,
          longLat: p.longLat,
          onAddress: p.onAddress,
          offAddress: p.offAddress,
          attachments: p?.attachments || [],
        }));
        // 合并
        siteMapping.push(...toggleSite);
        await store.create(toJS({ ...result, siteMapping }));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        // 原站点信息
        const siteMapping = store.currentStationInfos;
        const stationALL = store.selectStationInfos;
        // 新加入站点信息
        const flatSelectStationInfos = _.values(toJS(stationALL));
        const toggleSite = flatSelectStationInfos.map(({
          companyId,
          companyName,
          stationId,
          description,
          link,
          kind,
          longLat,
          onAddress,
          offAddress,
          attachments,
          name,
          cityId: id,
        }) => ({
          stationName: name,
          companyId,
          companyName,
          stationId,
          description,
          link,
          kind,
          longLat,
          onAddress,
          offAddress,
          attachments: attachments || [],
          cityId: id,
        }));
        // 合并
        siteMapping.push(...toggleSite);
        await store.update({ ...toJS(result), siteMapping });
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  /**
   * 同步站点
   * @param {*} 无
   * @returns {true}
   */
  const handleInitRoutes = async () => {
    try {
      await store.getRoutesInit();
      Message.success({ content: t`同步站点成功！` });
    } catch (error) {
      Message.error({ content: t`同步站点成功！`, duration: 7000 });
      throw error;
    }
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal({ visible: '', record: {} });
  };

  return (
    <div className="main-content" >
      <TauActionPanel
        className="action-panel"
        onSearch={handleOnSearch}
        actions={[
          {
            title: t`添加平台站点`,
            type: 'primary',
            onClick: handleCreate,
          },
          {
            title: t`刷新站点同步平台线路`,
            type: 'primary',
            onClick: handleInitRoutes,
          },
          {
            title: t`批量操作城市`,
            // type: 'primary',
            onClick: handleBatchSetting,
          },
          {
            title: expandAll ? t`合并全部` : t`展开全部`,
            // type: 'primary',
            onClick: () => setExpandAll(!expandAll),
          },
        ]}
        searchItems={[
          {
            name: 'companyIds',
            type: 'select',
            props: {
              placeholder: t`运营公司`,
              dataSource: companys,
              mode: 'multiple',
              style: { width: 300 },
            },
          },
          {
            name: 'state',
            type: 'select',
            props: {
              placeholder: t`状态`,
              value: stationState,
              dataSource: ENUMS._STATE,
              hasClear: false,
              style: { width: 80 },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜索`,
        }}
      />
      <div className="content">
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.stations)}
          expandAll={expandAll}
          expandedRowIndent={[300, 100]}
          expandedRowRender={(row) => (
            <ExpandedStationTable
              siteMapping={row.siteMapping}
              stationInfo={row}
            />
          )}
          rowSelection={{
            selectedRowKeys: selectData,
            onChange: (e) => {
              setSelectData(e);
            },
            columnProps: () => {
              return {
                lock: 'right',
                width: 38,
                align: 'center',
              };
            },
          }}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', { width: 88 }),
            column('cityName', { width: 88 }),
            column('areaName', { width: 88 }),
            column('name', {}),
            column('siteMapping', {}),
            column('type', {}),
            column('addressText', {}),
            column('longLat', {}),
            column('state', { width: 70 }),
            {
              title: t`操作`,
              dataIndex: 'stationNumber',
              width: 100,
              cell: (_, __, station) => (
                <>
                  <Button text type="primary" onClick={() => handleEditStation(station)} >{t`编辑`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.visible === 'edit' || modal.visible === 'add'}
        title={modal.visible === 'edit' ? t`编辑站点` : t`添加站点`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, close: `toClose$${Date.now()}` })}
        width="90%"
      >
        <DataForm
          id={modal?.record?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.visible === 'add' ? handleCreateStation : handleUpdate}
        />
      </Drawer>
    </div>
  );
});

export default Station;
